import axios from 'axios'
import config from '../config/index'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import storage from './storage'
const service = axios.create({
    baseURL: config.mockApi,
    timeout: 8000
})
service.defaults.headers.post['Content-Type'] = 'application/jsoncharset=UTF-8'
service.interceptors.request.use(config => {

    const tokenObj = storage.get('token')
    console.log(tokenObj, 'tokenObj');
    if (tokenObj) {
        config.headers['token'] = tokenObj
    }
    return config
})
service.interceptors.response.use(({ data }) => {
    const { msgCode, message } = data
    switch (msgCode) {
        case 400:
        case 405:
        case 500:
            ElMessage({
                showClose: true,
                message: message || '系统繁忙',
                type: 'error',
                duration: 1000
            });
            break
        case 501:
            ElMessage({
                showClose: true,
                message: message || '系统繁忙',
                type: 'error',
                duration: 1000
            });
            break
        case 401:
        case 402:
            useRouter().replace('/')
            storage.set('token', '')
            break
    }
    return data
})
export default service